package com.xm.web.utils;

import com.xm.web.entity.po.TbUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yousj
 * @since 2022-03-22
 */
public class SecurityUtil {

    /**
     * 当前用户id
     */
    public static Integer getCurrentUserId() {
        return getCurrentUser().getId();
    }

    /**
     * 当前用户
     */
    public static TbUser getCurrentUser() {
        return (TbUser) getAuthentication().getPrincipal();
    }

    /**
     * 权限集合
     */
    public static List<String> getAuthorities() {
        return getAuthentication().getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
    }

    private static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
